/*
* 四川生学教育科技有限公司
* Copyright (c) 2015-2025 Founder Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Founder. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the agreements
* you entered into with Founder.
*
*/
package cn.demo.io.demo1;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * @author WUANG (wa@sxw.cn)
 * @description @see http://ifeve.com/netty-2-3-4/
 * 连接不上，好像这个东西有点小问题
 * @date 2018/11/15 9:46
 * @slogon 站在巨人的肩膀上
 * @since 2.0.0
 */
public class Client {
    public static final int BUFFER_SIZE = 1024;

    public void startWork() throws Exception {
        SocketChannel clientChannel = SocketChannel.open();
        clientChannel.configureBlocking(false);

        Socket socket = clientChannel.socket();
        socket.setReuseAddress(true);
        socket.setReceiveBufferSize(BUFFER_SIZE);
        socket.setSendBufferSize(BUFFER_SIZE);

        boolean connected = clientChannel.connect(new InetSocketAddress(NBTest.PORT));

        Selector selector = Selector.open();
        clientChannel.register( selector, SelectionKey.OP_READ);
        /*if (connected)
        {
            clientChannel.register( selector, SelectionKey.OP_READ, ioHandler);
        }
        else
        {
            clientChannel.register( selector, SelectionKey.OP_CONNECT, ioHandler);
        }*/

        String newData = "New String to write to file..." + System.currentTimeMillis();
        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());
        buf.flip();
        while(buf.hasRemaining()) {
            clientChannel.write(buf);
        }
    }

    public static void main(String[] args) {
        try {
            new Client().startWork();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}